#!/bin/bash
#set -euo pipefail # 严格模式：错误退出、未定义变量报错

# --------------------------
# 检查.env文件是否存在
# --------------------------
if [ ! -f ".env" ]; then
    echo "[错误] .env 文件未找到，请确认当前目录下存在该文件"
    exit 1
fi

# --------------------------
# 加载环境变量
# --------------------------
source .env

# --------------------------
# 验证必要环境变量是否定义
# --------------------------
required_vars=(
    "GITLAB_SSL_CONFIG_PATH"
    "NGINX_SSL_CERTIFICATE_KEY"
    "NGINX_SSL_CERTIFICATE"
    "GITLAB_HOSTNAME"
)

missing_vars=()
for var in "${required_vars[@]}"; do
    if [ -z "${!var:-}" ]; then
        missing_vars+=("$var")
    fi
done

if [ ${#missing_vars[@]} -gt 0 ]; then
    echo "[错误] 以下必要环境变量未定义:"
    printf ' - %s\n' "${missing_vars[@]}"
    exit 1
fi

# --------------------------
# 创建证书目录（如不存在）
# --------------------------
target_dir="./${GITLAB_SSL_CONFIG_PATH}"
if [ ! -d "$target_dir" ]; then
    echo "[信息] 创建证书目录: $target_dir"
    mkdir -p "$target_dir"
    chmod 755 "$target_dir"
else
    echo "[信息] 证书目录已存在: $target_dir"
fi

# --------------------------
# 检查证书文件是否已存在
# --------------------------
cd "$target_dir"
cert_key_path="./${NGINX_SSL_CERTIFICATE_KEY}"
cert_path="./${NGINX_SSL_CERTIFICATE}"

if [ -f "$cert_key_path" ] && [ -f "$cert_path" ]; then
    echo "[信息] SSL 证书和密钥已存在，跳过生成步骤"
    echo "密钥路径: $(realpath "$cert_key_path")"
    echo "证书路径: $(realpath "$cert_path")"
    exit 0
fi

# 检查 openssl 命令是否可用
if ! command -v openssl &>/dev/null; then
    echo "[错误] openssl 命令不可用，请安装 openssl"
    exit 1
fi

# --------------------------
# 生成 SSL 密钥和证书
# --------------------------
echo "[信息] 开始生成 SSL 密钥和证书..."
openssl ecparam -genkey -name secp384r1 -out "$cert_key_path"
openssl req -x509 -new \
    -key "$cert_key_path" \
    -sha384 \
    -days 365 \
    -subj "/CN=${GITLAB_HOSTNAME}" \
    -out "$cert_path"

chmod 644 $cert_path
chmod 600 $cert_key_path

# --------------------------
# 验证生成结果
# --------------------------
if [ -f "$cert_key_path" ] && [ -f "$cert_path" ]; then
    echo "[成功] 文件已生成:"
    echo "密钥路径: $(realpath "$cert_key_path")"
    echo "证书路径: $(realpath "$cert_path")"
else
    echo "[错误] 文件生成失败，请检查 OpenSSL 命令输出"
    exit 1
fi
